define(["angularAMD", "moment"], function (angularAMD, moment) {
    angularAMD.service('B0207Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog', '$calculater', "$gallery", "$mddProvider", "$timeout",
        function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog,$calculater, $gallery, $mddProvider, $timeout) {
            /**
             * options = {
             *     plotItem:{},
             *     machine_no:'',
             *     type: '', //首檢=0, 巡檢=2
             *     feedback: function
             * }
            **/
            this.init = function (options) {
                var picLimitNum = 5;

                // 20200110 modify by WeiTing for M#66287 - 判斷車間作業站基本資料是否有設定 SPC檢驗。
                function judgeSpcProcess(area, check_qty, run_type,dialog,inspectionInfo, feedback){
                    var content = { 
                        detail_SN:dialog.detail_SN,
                        op_no: options.plotItem.op_no,
                        plot_no: options.plotItem.plot_no,
                        employee_no:  inspectionInfo ? inspectionInfo.employee_no: config.cache.account,
                        area_no: area.area_no,
                        machine_no: options.machine_no || options.area_no,
                        check_qty: check_qty, // 預設檢驗數量是 1，當 SPC檢驗時，可以更改檢驗數量。
                        check_time:moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                        productid:options.product_id,//2020200108 modify by 韋齊 for M#66287 新增品號
                        qc_result: 'Y',
                        qc_type: options.type, //首檢qc_type=0, 巡檢qc_type=1
                        qc_reason_detail:[],
                        run_type: run_type, // run_type=0：一開始判斷要走SPC還是標準版帶 0 ; run_type=1：SPC檢驗和標準版檢驗送回資料帶 1。
                        plot_status: options.plotItem.status
                    };
                   
                //    Object.assign(content,{ employee_no: dialog.inspectionInfo.employee_no?inspectionInfo.employee_no: config.cache.account,});
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.first_piece_check_process',
                        content: content,
                        success: function (data, response) {
                            if(feedback)
                                feedback(data, response);
                        }
                    });
                };

                // 20200226 modify by WeiTing for M#67360 - SPC檢驗，要改成開窗，讓使用者可以自己調整檢驗數量，在按確定送回檢驗。
                var spcDialog = function(area,data){
                    $mddProvider.UseForm('B0207_judgeSpc', () =>{
                        $mdDialog.dialog(
                            'module/moduleB/program/B02/B0207/judgeSpc.tmp.html',
                            function (dialog) {
                                return {
                                    data: data,
                                    detail_SN:[],
                                    css_url:'module/moduleB/program/B02/B0207/judgeSpc.css',
                                    parent:options.parent,
                                    _title: $filter('translate')('B0207.title_' + options.type),
                                    inspectionInfo: {
                                      
                                        machine_no:options.machine_no || options.area_no,
                                        op_no: options.plotItem.op_no,
                                        plot_no: options.plotItem.plot_no,
                                        employee_no:  config.cache.account,
                                        legal_employee_no: 'Y',
                                        area_no:area.area_no,
                                        check_qty: data.NeedSN ? 0 : 1,
                                        check_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                                    },
                                    back: function () {
                                        dialog.hide();
                                    },
                                    init:function(){
                                        // dialog._event['check_qty'].isDisabled = 'Y';                       
                                        dialog.detail_SN = [];
                                     
                                        if( dialog.data.NeedSN){
                                            dialog._event['serialNumberList'].isShown = 'Y';
                                            dialog._event['check_qty'].isDisabled = 'Y';     
                                            dialog.data.NeedSN ? dialog._event['serialNumberCollect'].isShown = 'Y' : dialog._event['serialNumberCollect'].isShown = 'N';
                                            dialog.data.NeedSN ? dialog._event['list'].isShown = 'Y' : dialog._event['list'].isShown = 'N';   
                                        }
                                      
                                    },
                                    //調整過人員代碼，則需重新檢合
                                    input_employee_no: function ()
                                    {

                                        dialog.inspectionInfo.legal_employee_no = 'N';

                                    },
                                    check_employee_no: function ()
                                    {
                                       //20230217 modify by shiwl for M#0127357 取得检验人员
                                       $MMWService.showQueryListPNIG({
                                               form_name:"PageNo_119",
                                               pageRecord: 50,
                                               condition: [
                                                       { name: $filter('translate')('common.queryList.employee_c'), column_name: 'UserNo', query_mode: '2', value: dialog.inspectionInfo.employee_no }
                                               ],
                                               header: [
                                                       { label: $filter('translate')('common.queryList.employee_c'), code: 'user_no' },
                                                       { label: $filter('translate')('common.queryList.employee_n'), code: 'user_name' }
                                               ],
                                               setCondition: function (conditions) {
                                                       conditions.push(
                                                               { column_name: 'IssueState', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                                                       );
                                                       return conditions;
                                               },
                                               selectCode:dialog.inspectionInfo.employee_no || '',
                                               confirm: function (selectItem, dialog2) {
                                                       dialog.inspectionInfo.employee_no = selectItem.user_no;
                                                       dialog2.hide();
                                               }
                                         });                                     
                                   },
                                    //檢合與沒有檢合的display
                                    isCheck: function (legal_employee_no) {
                                        switch (legal_employee_no){
                                            case 'N':
                                                return 'red';
                                            case 'Y':
                                                return 'green';
                                        }
                                        return 'red';
                                    },
                                    removeAll: function (index) {
                                       
                                        dialog.detail_SN = [];
                                    },
                                    removeRow: function (index) {
                                        // 20211110 modify by chenshibo for#102898: 标准巡检多行数据不能够定向去除
                                        dialog.detail_SN.splice(index, 1);
                                        dialog.inspectionInfo.check_qty = dialog.detail_SN.length;
                                    },
                                    input_qty: function (event) {
                                        var target = event.currentTarget;
                                        angular.element(target).addClass('is-focus');
                                        $calculater.open(function (num, calDialog) {

                                            if(options.type ==2 || options.type ==4){
                                                    var checkNumber = options.queryNumber.input_qty-options.queryNumber.defect_qty;
                                                if ((+num) > (+checkNumber)) {
                                                        $rootScope.showAlert($filter('translate')('B0207.msg.check_qty_gt') + checkNumber);
                                                    } else {
                                                        dialog.inspectionInfo.check_qty = num;
                                                        angular.element(target).removeClass('is-focus');
                                                        calDialog.hide();
                                                }
                                            } else {
                                                if ((+num) > (+dialog.inspectionInfo.max_qty)) {
                                                        $rootScope.showAlert($filter('translate')('B0207.msg.check_qty_gt') + dialog.inspectionInfo.max_qty);
                                                } else {
                                                        dialog.inspectionInfo.check_qty = num;
                                                        angular.element(target).removeClass('is-focus');
                                                        calDialog.hide();
                                                }
                                            }
                                                
                                            },
                                            function (calDialog) {
                                                angular.element(target).removeClass('is-focus');
                                                calDialog.hide();
                                            },
                                            {
                                                defaultNum: dialog.inspectionInfo.check_qty,
                                                decimal: true
                                            });
                                    },
                                    // 20200226 modify by WeiTing for M#67360 - SPC檢驗，要改成開窗，讓使用者可以自己調整檢驗數量。
                                    judgeSpcProcess: function(){
                                        if(dialog.detail_SN.length== 0 &&data.NeedSN){
                                           $rootScope.showAlert($filter('translate')('B0207.you_must_swipe_at_least_one_serial_number'));    
                                           return;
                                        } else {
                                           judgeSpcProcess(area, dialog.inspectionInfo.check_qty, run_type = 1,dialog,dialog.inspectionInfo,function(data, response){
                                             dialog.hide();
                                             $rootScope.showToast(response.Message);
                                          });
                                        }
                                       
                                    },
                                    _fn: {
                                        confirm: {
                                            click: () => {
                                                dialog.judgeSpcProcess(dialog);
                                            }
                                        }
                                    },
                                    _event:{
                                      'serialNumberList':{
                                         isShown:"N",
                                      
                                        },
                                      'serialNumberCollect':{
                                         isShown:"N",
                                    
                                        change(value,$event){
                                      
                                           if($event.event.charCode == 13){
                                                const data = {
                                                   serial_no:value
                                                 }
                                              const hasValue = dialog.detail_SN.filter(item=> item.serial_no == data.serial_no);
                                              if(hasValue.length) {
                                                  $rootScope.showToast($filter('translate')('B0207.msg.serial_number_is_repeatedly_brushed_in'));
                                                  return false;
                                              } else { 
                                                dialog.detail_SN.push(data);
                                                dialog.inspectionInfo.check_qty = dialog.detail_SN.length;
                                                dialog.serialNumberCollect = "";
                                              }
                                           }   
                                        }
                                      },
                                      'check_qty':{ isDisabled :"N" },
                                      'list':{
                                        isShown:"N" 
                                      }
                                    }
                                };
                            }
                        );
                    })
                };

                function firstPieceCheckProcess(dialog) {
                    var content = {
                        station_no: dialog.inspectionInfo.station_no,
                        op_no: dialog.inspectionInfo.op_no,
                        plot_no: dialog.inspectionInfo.plot_no,
                        employee_no: dialog.inspectionInfo.employee_no,
                        area_no: dialog.inspectionInfo.area_no,
                        machine_no: dialog.inspectionInfo.machine_no,
                        check_qty: dialog.inspectionInfo.check_qty,
                        defect_qty: dialog.inspectionInfo.defect_qty,
                        check_time: dialog.inspectionInfo.check_time,
                        pcsno: dialog.inspectionInfo.pcsno,
                        // 20201127 modify by 外包 for M#81457: 添加创建人/首检申请
                        creator: dialog.inspectionInfo.operator_no, 
                        apply_qc_type: dialog.inspectionInfo.apply_qc_flag ? '2' : '',
                        qc_result: 'Y',
                        // 20200110 modify by WeiTing for M#66287 - 改成要傳給後台 qc_type 等於 -1 才能走原本標準版的流程。
                        qc_type: (options.type==='0')?'-1':'-2',
                        type: dialog.inspectionInfo.type,
                        checklist_detail: dialog.inspectionInfo.checklist_detail,
                        image_detail: [],
                        qc_reason_detail: dialog.inspectionInfo.qc_reason_detail,
                        qc_record_param: dialog.inspectionInfo.qc_record_param,
                        run_type: 1, // run_type=0：一開始判斷要走SPC還是標準版帶 0 ; run_type=1：SPC檢驗和標準版檢驗送回資料帶 1。
                        plot_status: options.plotItem.status
                    };
                    if(dialog.inspectionInfo.is_smt)
                    {
                        if(dialog.inspectionInfo.smt_psc_type.trim() != "")
                            content.smt_pcs_type = dialog.inspectionInfo.smt_psc_type;  
                        if(dialog.inspectionInfo.smt_op_seq.trim() != "")
                            content.smt_op_seq = dialog.inspectionInfo.smt_op_seq;
                    }
                    if((+content.defect_qty) != 0)
                        content.qc_result = 'N';

                    for(var i=0;i<dialog.picSrcArray.length;i++){
                        var picSrc = dialog.picSrcArray[i];
                        content.image_detail.push({
                            image_src:picSrc,
                            image_seq:i,
                            image_format:'jpg'
                        });
                    }

                    //20180503 modify by 李栋 for mantis#0046586
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.first_piece_check_process',
                        content: content,
                        success: function () {
                            //20180416 modify by 李栋 for mantis#0045407
                            $rootScope.showToast($filter('translate')('B0207.msg.success_' + options.type));
                            dialog.hide();
                            if(options.feedback)
                                options.feedback();
                        }
                    });
                }

                function opqcreason_info_get(feedback){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.op_qcreason_info_get',
                        content: {
                            op_no: options.plotItem.op_no,
                            lot_no: options.plotItem.plot_no,
                            machine_no: options.machine_no || '',
                            area_no: options.area_no || '',
                            type: options.type || '3'  //3=自動判斷
                        },
                        success: function (data) {
                            if(feedback)
                                feedback(data);
                        }
                    });
                }

                function inj_eqp_info_get(feedback) {
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.inj_eqp_data_info_get',
                        content: {
                            machine_no: options.machine_no || ''
                        },
                        success: function (data) {
                            if (feedback)
                                feedback(data);
                        }
                    });
                }

                var openDialog = function (badcodeList, data, injData, spc_flag) {
                    $mddProvider.UseForm('B0207Service', () => {
                        $mdDialog.dialog(
                            'module/moduleB/program/B02/B0207/B0207.html',
                            function (dialog) {
                                return {
                                    css_url:'module/moduleB/program/B02/B0207/B0207.css',
                                    parent:options.parent,
                                    server_url:'http://'+config.server.ip+':'+config.server.port,
                                    _title: $filter('translate')('B0207.title_' + options.type),
                                    page_nume:1,
                                    inspectionInfo: {
                                        machine_no:options.machine_no || options.area_no,
                                        op_no: options.plotItem.op_no,
                                        plot_no: options.plotItem.plot_no,
                                        employee_no: config.cache.account,
                                        operator_no: config.cache.account,
                                        legal_employee_no: 'Y',
                                        legal_operator_no: 'Y',
                                        apply_qc_flag: false,
                                        spc_flag: spc_flag,
                                        type_flag: options.type,
                                        area_no:data.area_no,
                                        type:data.type,
                                        check_qty: (options.plotItem.qty >= 1) ? '1' : options.plotItem.qty,
                                        max_qty:options.plotItem.qty,
                                        check_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                                        checklist_detail: [],
                                        image_detail: [],
                                        qc_reason_detail: data.qc_reason_detail,
                                        equipment_no: injData.equipment_display || '',
                                        qc_record_param: injData.qc_record_param || '',
                                        is_inj: injData.is_inj || '',
                                        isClose: false,
                                        is_smt:data.is_smt,
                                        smt_psc_type:'',
                                        smt_psc_type_name:'',
                                        smt_op_seq:''
                                    },
                                    //20230314 add by 勝堃 for M# 0121894: MES序列号检验优化。 
                                    NeedSN: options.needsn,
                                    init:function(){
                                        
                                    },
                                    pages: ['qc_reason_detail', 'pic', 'detail_report'],
                                    // 20200521 add by Oliver for 頁籤功能
                                    changePages:function(targetPage){
                                        dialog.pages.forEach((page, index) => {
                                            if(index === targetPage) {
                                                dialog._event[page].isShown = 'Y';
                                            } else {
                                                dialog._event[page].isShown = 'N';
                                            }

                                        });
                                    },
                                    check_operator_no: function () {
                                        //20230217 modify by shiwl for M#0127357 取得操作人员
                                        $MMWService.showQueryListPNIG({
                                                form_name:"PageNo_119",
                                                pageRecord: 50,
                                                condition: [
                                                        { name: $filter('translate')('common.queryList.employee_c'), column_name: 'UserNo', query_mode: '2', value: dialog.inspectionInfo.operator_no }
                                                ],
                                                header: [
                                                        { label: $filter('translate')('common.queryList.employee_c'), code: 'user_no' },
                                                        { label: $filter('translate')('common.queryList.employee_n'), code: 'user_name' }
                                                ],
                                                setCondition: function (conditions) {
                                                        conditions.push(
                                                                { column_name: 'IssueState', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                                                        );
                                                        return conditions;
                                                },
                                                selectCode:dialog.inspectionInfo.operator_no || '',
                                                confirm: function (selectItem, dialog2) {  
                                                      
                                                        dialog.inspectionInfo.operator_no = selectItem.user_no;
                                                        dialog2.hide();
                                                }
                                          });
                                        
                                          
                                    },                                    
                                    check_employee_no: function () {
                                        //20230217 modify by shiwl for M#0127357 取得检验人员
                                        $MMWService.showQueryListPNIG({
                                                form_name:"PageNo_119",
                                                pageRecord: 50,
                                                condition: [
                                                        { name: $filter('translate')('common.queryList.employee_c'), column_name: 'UserNo', query_mode: '2', value: dialog.inspectionInfo.employee_no }
                                                ],
                                                header: [
                                                        { label: $filter('translate')('common.queryList.employee_c'), code: 'user_no' },
                                                        { label: $filter('translate')('common.queryList.employee_n'), code: 'user_name' }
                                                ],
                                                setCondition: function (conditions) {
                                                        conditions.push(
                                                                { column_name: 'IssueState', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                                                        );
                                                        return conditions;
                                                },
                                                selectCode:dialog.inspectionInfo.employee_no || '',
                                                confirm: function (selectItem, dialog2) {
                                                        dialog.inspectionInfo.employee_no = selectItem.user_no;
                                                        dialog2.hide();
                                                }
                                          });                                     
                                    },
                                    isCloseClick: function(){
                                        if(!dialog.isClose){
                                            dialog.isClose = true;
                                        } else {
                                            dialog.isClose = false;
                                        };
                                    },
                                    loadSmtSerialNum :function(event){
                                        var check = typeof dialog.inspectionInfo.pcsno !== 'undefined';
                                        dialog.inspectionInfo.smt_psc_type ='';
                                        dialog.inspectionInfo.smt_psc_type_name ='';
                                        dialog.inspectionInfo.smt_op_seq ='';
                                        if(dialog.inspectionInfo.is_smt && check && dialog.inspectionInfo.pcsno.trim() != "" && event.which === 13)
                                        {
                                            $MMWService.sendToServer({
                                                uri: 'ServicesSTD.Module_WIP.inj_eqp_data_info_get',
                                                content : {
                                                    lot_no:dialog.inspectionInfo.plot_no,
                                                    op_no:dialog.inspectionInfo.op_no,
                                                    pcs_no:dialog.inspectionInfo.pcsno
                                                },
                                                success : function(data)
                                                {
                                                    if(data.pcs_type.trim().length > 0)
                                                        dialog.inspectionInfo.smt_psc_type = data.pcs_type;
                                                    if(data.op_seq.trim().length > 0)
                                                        dialog.inspectionInfo.smt_op_seq = data.op_seq;
                                                    if(data.pcs_type =="pcs_no")
                                                        dialog.inspectionInfo.smt_psc_type_name = $filter('translate')('B0207.js.product_num');
                                                    else if(data.pcs_type =="panel_no")
                                                        dialog.inspectionInfo.smt_psc_type_name = $filter('translate')('B0207.js.plate_num');
                                                }
                                            });
                                        }
                                    },
                                    loadSmtSeqNum:function(){
                                        var check = typeof dialog.inspectionInfo.pcsno !== 'undefined';
                                        //var check3 = dialog.inspectionInfo.smt_psc_type.trim().length >0;
                                        //var check4 = dialog.inspectionInfo.smt_op_seq.trim().length >0;
                                        if(dialog.inspectionInfo.is_smt && check && dialog.inspectionInfo.pcsno.trim().length >0)
                                        {
                                            $MMWService.showQueryListPNIG({
                                                form_name: 'PageNo_116',
                                                header: [
                                                    {label:$filter('translate')('B0207.js.process'), code:'smt_op_seq'},
                                                    {label:$filter('translate')('B0207.js.process_name'), code:'smt_op_name'}
                                                ],
                                                setCondition:function(conditions){
                                                    conditions.push({column_name:'c.BASELOTNO', query_mode:'0', value:dialog.inspectionInfo.plot_no, merge_condition_model:'AND' });
                                                    return conditions;
                                                },
                                                selectCode:dialog.inspectionInfo.smt_op_seq||'',
                                                confirm : function(selectItem){
                                                    dialog.inspectionInfo.smt_op_seq = selectItem.smt_op_seq
                                                }
                                            });
                                        }

                                    },
                                    loadInspectionReasonList: function (item) {
                                        $rootScope.showQueryList({
                                            key:'page_no',
                                            selectCode:item?item.page_no:'',
                                            header : [
                                                {label: $filter('translate')('common.queryList.badReason_c'), code:'page_no'},
                                                {label: $filter('translate')('common.queryList.badReason_n'), code:'page_name'}
                                            ],
                                            query: function(conditions, feedback){
                                                feedback(badcodeList);
                                            },
                                            confirm: function(selectItem, radioDialog){
                                                if(item){
                                                    item.item_code = selectItem.page_no;
                                                    item.page_no = selectItem.page_no;
                                                    item.page_name = selectItem.page_name;
                                                } else {
                                                    dialog.inspectionInfo.checklist_detail.push({
                                                        item_code: selectItem.page_no,
                                                        page_no: selectItem.page_no,
                                                        page_name: selectItem.page_name,
                                                        item_qty: 1
                                                    });
                                                }
                                                radioDialog.hide();
                                            }
                                        });
                                    },
                                    addRow: function(){dialog.loadInspectionReasonList();},
                                    removeRow: function (index) {
                                        // 20211110 modify by chenshibo for#102898: 标准巡检多行数据不能够定向去除
                                        dialog.inspectionInfo.checklist_detail.splice(index, 1);
                                    },
                                    //調整過人員代碼，則需重新檢合
                                    input_employee_no: function () {
                                        dialog.inspectionInfo.legal_employee_no = 'N';
                                    },
                                  
                                    input_operator_no: function () {
                                        dialog.inspectionInfo.legal_operator_no = 'N';

                                      
                                    },
                                    //檢合與沒有檢合的display
                                    isCheck: function (legal_employee_no) {
                                        switch (legal_employee_no){
                                            case 'N':
                                                return 'red';
                                            case 'Y':
                                                return 'green';
                                        }
                                        return 'red';
                                    },
                                    //檢合與沒有檢合的display
                                    isOperatorCheck: function (legal_operator_no) {
                                        switch (legal_operator_no) {
                                            case 'N':
                                                return 'red';
                                            case 'Y':
                                                return 'green';
                                        }
                                        return 'red';
                                    },
                              
                                    change_apply_qc: function () {
                                        dialog.inspectionInfo.apply_qc_flag = !dialog.inspectionInfo.apply_qc_flag;
                                    },
                                    input_qty: function (event) {
                                        var target = event.currentTarget;
                                        angular.element(target).addClass('is-focus');
                                        $calculater.open(function (num, calDialog) {
                                            // 20211110 modify by shiwl for#0122742: 针对巡检、末检，如果已验不良数量（未出站）>=R状态数量，则不允许执行检验
                                            // if ((+num) > (+dialog.inspectionInfo.max_qty)) {                                        
                                                if(options.type ==2 || options.type ==4){
                                                    var checkNumber = options.queryNumber.input_qty-options.queryNumber.defect_qty;
                                                    if ((+num) > (+checkNumber)) {
                                                            $rootScope.showAlert($filter('translate')('B0207.msg.check_qty_gt') + checkNumber);
                                                        } else {
                                                            dialog.inspectionInfo.check_qty = num;
                                                            angular.element(target).removeClass('is-focus');
                                                            calDialog.hide();
                                                        }
                                                } else {
                                                    if ((+num) > (+dialog.inspectionInfo.max_qty)) {
                                                            $rootScope.showAlert($filter('translate')('B0207.msg.check_qty_gt') + dialog.inspectionInfo.max_qty);
                                                        } else {
                                                            dialog.inspectionInfo.check_qty = num;
                                                            angular.element(target).removeClass('is-focus');
                                                            calDialog.hide();
                                                        }
                                                }
                                            
                                            },
                                            function (calDialog) {
                                                angular.element(target).removeClass('is-focus');
                                                calDialog.hide();
                                            },
                                            {
                                                defaultNum: dialog.inspectionInfo.check_qty,
                                                decimal: true
                                            });
                                    },
                                    input_defect_qty: function (event, item) {
                                        var target = event.currentTarget;
                                        angular.element(target).addClass('is-focus');
                                        $calculater.open(function (num, calDialog) {
                                                angular.element(target).removeClass('is-focus');
                                                item.item_qty = num;
                                                calDialog.hide();
                                            },
                                            function (calDialog) {
                                                angular.element(target).removeClass('is-focus');
                                                calDialog.hide();
                                            },
                                            {
                                                defaultNum: item.item_qty,
                                                decimal: true
                                            }
                                        );
                                    },
                                    InRange: function(item){
                                        // 20210114 modify by WeiTing for M#85202: 增加判斷 reason_value 是空字串、null、undefined 時，返回 false。
                                        if(item.reason_value == null || item.reason_value === '') {
                                            return false;
                                        }

                                        if(item.check_type == 1 && !isNaN(item.reason_value)){
                                            if((+item.mini_value) <= (+item.reason_value)
                                                && (+item.reason_value) <= (+item.max_value)){
                                                return true;
                                            } else {
                                                return false;
                                            }
                                        } else {
                                            return false;
                                        }
                                    },
                                    back: function () {
                                        dialog.hide();
                                    },
                                    checkEmployeeNo: ()=>{
                                    
                                        return new Promise(async (resolve, reject) => {
                                                let result;
                                                $MMWService.sendToServer({
                                                        uri: "ServicesSTD.Module_SYS.user_information_get",
                                                        content: {
                                                                employee_no: dialog.inspectionInfo.employee_no,
                                                                report_datetime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                                                                machine_no: dialog.inspectionInfo.machine_no,
                                                                return_type: '00'
                                                            },
                                                        success: (data) => (result = resolve(data)),
                                                        error:(data) => (result = resolve(data))
                                                    });
                                               return result;
                                         });                                      
                                    },
                                    echeckOperatorNo: ()=>{  
                                        return new Promise(async (resolve, reject) => {
                                                let result;
                                                $MMWService.sendToServer({
                                                        uri: "ServicesSTD.Module_SYS.user_information_get",
                                                        content: {
                                                                employee_no: dialog.inspectionInfo.operator_no,
                                                                report_datetime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                                                                machine_no: dialog.inspectionInfo.machine_no,
                                                                return_type: '00'
                                                            },
                                                        success: (data) => (result = resolve(data)),
                                                        error:(data) => (result = resolve(data))
                                                    });
                                               return result;
                                         });               
                                    },
                                    confirm: async()=> {
                                      
                                        var defect_qty = 0, msg = '';

                                        //20200831 modify by Dustdusk for M#77210:
                                        dialog.inspectionInfo.qc_reason_detail.forEach(function(item, index){
                                            //此項目須判斷是否要輸入不良
                                            // 20231221 modify by wenwei for M#153794: [MSSQL] [H5][首巡自末检]质量检验检验项目不合格是否需要录入不良问题
                                            if(item.is_inputscrap == '1'){
                                                // switch btn 沒選過 / false
                                                if(item.check_type == 0 && (item.reason_value == '' || item.reason_value == 'false')){
                                                    // 檢查不良現象是否有新增不良原因
                                                    if(dialog.inspectionInfo.checklist_detail.length == 0){
                                                        msg += $filter('translate')('B0207.check_list.column1') + item.reason_no + '、';
                                                    }
                                                } else if(item.check_type == 1){
                                                    // 有輸入值
                                                    if(item.reason_value !== '' && item.reason_value !== null) {
                                                        // 符合標準
                                                        if((+item.mini_value) <= (+item.reason_value) && (+item.reason_value) <= (+item.max_value)) return
                                                    }
                                                    // 檢查不良現象是否有新增不良原因
                                                    if(dialog.inspectionInfo.checklist_detail.length == 0){
                                                        msg += $filter('translate')('B0207.check_list.column1') + item.reason_no + '、';
                                                    }
                                                }
                                            }
                                        });
                                        if(msg != ''){
                                            if(dialog.inspectionInfo.checklist_detail.length == 0){
                                                $rootScope.showAlert(msg + $filter('translate')('B0207.msg.checkitem_need_badreason'));
                                                return;
                                            }
                                        }

                                        //20230613 add by Ruke for M#137443: [6.0.1Patch] [MSSQL]MES序列号检验问题
                                        //作业站NEESSN选择全选序列号报工/逐个扫码报工时，如果序列号栏位没有输入值，点击【确定】，目前也可以成功执行，没有验证此栏位必须有值
                                        if (dialog.NeedSN != '1' && (dialog.inspectionInfo.pcsno == undefined || dialog.inspectionInfo.pcsno == '')) {
                                            $rootScope.showAlert($filter('translate')('B0207.msg.serial_number_is_empty'));
                                            return;
                                        }


                                        dialog.inspectionInfo.checklist_detail.forEach(function(item, index){
                                            item.item_seq = index;
                                            defect_qty = $calculater.decimalAdd(defect_qty, item.item_qty);
                                        });
                                        if ((+defect_qty) > (+dialog.inspectionInfo.check_qty)) {
                                                msg = $filter('translate')('B0207.msg.check_qty_lt_defect_qty');                                    
                                         }  
                                       
                                       var  operatorNo =  await dialog.echeckOperatorNo(); // 校验 操作人员和处理人员
                                       var  employeeNo = await dialog.checkEmployeeNo();   
                                       if(operatorNo.hasOwnProperty('isSuccess')){
                                          msg = operatorNo.Message;  
                                       }else if(employeeNo.hasOwnProperty('isSuccess')){
                                           msg = employeeNo.Message;  
                                       }
                                       
                                       if(msg == ''){
                                          dialog.inspectionInfo.defect_qty = defect_qty;        
                                          firstPieceCheckProcess(dialog);
                                       }  else {
                                        $rootScope.showAlert(msg);
                                      }
                                      
                                    },
                                    picSrcArray : [],
                                    //拍照
                                    pic_add : function(){
                                        if(dialog.picSrcArray.length < picLimitNum){
                                            if(typeof(navigator.camera) !== 'undefined'){
                                                //回傳URI
                                                navigator.camera.getPicture(
                                                    function(imageURI) {
                                                        if($rootScope.compressImage)
                                                        {
                                                            $rootScope.compressImage(imageURI, 
                                                                function(data){  
                                                                    dialog.picSrcArray.push(data);
                                                                    $rootScope.$apply();
                                                                    }); 
                                                        }
                                                        else
                                                        {
                                                            dialog.picSrcArray.push(imageURI);
                                                            $rootScope.$apply();
                                                        }
                                                        //$scope.data.scrollLeft = document.getElementById('img-tile-list').clientWidth;
                                                    },
                                                    function(message) {
                                                        //alert('Failed because: ' + message);
                                                    },
                                                    {
                                                        quality: 50,
                                                        destinationType: Camera.DestinationType.DATA_URL
                                                    }
                                                );
                                            } else if(window.nodeRequire){     
                                                //回傳URI

                                                try {
                                                    // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                                                    const { remote } = window.nodeRequire('electron');
                                                    if(remote) {
                                                        remote.dialog.showOpenDialog({
                                                            properties: ['openFile', 'multiSelections'],
                                                            filters: [
                                                                {name: 'Images', extensions: ['jpg', 'png', 'gif', 'bmp']}
                                                            ]
                                                        },function(fileList){
                                                            $rootScope.showLoading();
                                                            $rootScope.$apply();
                                                            setTimeout(function(){
                                                                if(fileList){
                                                                    if(fileList.length == 0){
                                                                        //
                                                                    } else if((dialog.picSrcArray.length + fileList.length) > picLimitNum){
                                                                        $rootScope.showAlert($filter('translate')('B0207.msg.pic_limit', {num:picLimitNum}));
                                                                    } else {
                                                                        var fs = window.nodeRequire('fs');
                                                                        fileList.forEach(function(fileName){
                                                                            var image = fs.readFileSync(fileName);
                                                                            if(image)
                                                                                dialog.picSrcArray.push(new Buffer(image).toString('base64'));
                                                                        });
                                                                    }
                                                                }
                                                                $rootScope.hideLoading();
                                                                $rootScope.$apply();
                                                            });
                                                        });
                                                    } else {
                                                        const remote = window.nodeRequire('@electron/remote');
                                                        remote.dialog.showOpenDialog({
                                                            properties: ['openFile', 'multiSelections'],
                                                            filters: [
                                                                {name: 'Images', extensions: ['jpg', 'png', 'gif', 'bmp']}
                                                            ]
                                                        }).then((result) => {
                                                            $rootScope.showLoading();
                                                            $rootScope.$apply();
                                                            setTimeout(function(){
                                                                if(result){
                                                                    if(result.filePaths.length == 0){
                                                                        //
                                                                    } else if((dialog.picSrcArray.length + result.filePaths.length) > picLimitNum){
                                                                        $rootScope.showAlert($filter('translate')('B0207.msg.pic_limit', {num:picLimitNum}));
                                                                    } else {
                                                                        var fs = window.nodeRequire('fs');
                                                                        result.filePaths.forEach(function(fileName){
                                                                            var image = fs.readFileSync(fileName);
                                                                            if(image)
                                                                                dialog.picSrcArray.push(new Buffer(image).toString('base64'));
                                                                        });
                                                                    }
                                                                }
                                                                $rootScope.hideLoading();
                                                                $rootScope.$apply();
                                                            });
                                                        });
    
                                                    }
                                                } catch (error) {
                                                    $('body').append('<input id="fileDialog" type="file" accept=".jpg,.png,.gif,.bmp" multiple size="5" >');
                                                    var file_field = $('#fileDialog');
                                                    file_field.on('change', function(){
                                                        if(file_field[0].files && file_field[0].files.length>0){
                                                            var fileList = [];
                                                            for(var i =0;i<file_field[0].files.length;i++){
                                                                fileList.push(file_field[0].files[i].path);
                                                            }
                                                            if((dialog.picSrcArray.length + fileList.length) > picLimitNum){
                                                                $rootScope.showAlert($filter('translate')('B0207.msg.pic_limit', {num:picLimitNum}));
                                                            } else {
                                                                var fs = window.nodeRequire('fs');
                                                                fileList.forEach(function(fileName){
                                                                    var image = fs.readFileSync(fileName);                      
                                                                    if(image){
                                                                        if($rootScope.compressImage)
                                                                        {
                                                                            $rootScope.compressImage(new Buffer(image).toString('base64'), 
                                                                            function(data){dialog.picSrcArray.push(data)});  
                                                                        }
                                                                        else{
                                                                            dialog.picSrcArray.push(new Buffer(image).toString('base64'))
                                                                        }
                
                                                                    }
                                                                });
                                                            }
                                                        }
                                                        file_field.remove();
                                                    });
                                                    file_field.click();
                                                    
                                                }

                                    
                                            } else {
                                                $rootScope.showAlert($filter('translate')('common.msg.cant_use_camera'));
                                            }
                                        } else {
                                            $rootScope.showAlert($filter('translate')('B0207.msg.pic_limit', {num:picLimitNum}));
                                        }
                                    },
                                    pic_delete : function(index){
                                        dialog.picSrcArray.splice(index,1);
                                    },
                                    pic_open : function(index){
                                        $gallery.show('#'+(index+1), 'data:image/jpeg;base64,'+dialog.picSrcArray[index], function(){

                                        });
                                    },
                                    open_checkPic: function(item){
                                        $gallery.show(item.reason_no, dialog.server_url+item.picture_path, function(){});
                                    },
                                    //记数参数履历
                                    open_qc_record: function () {
                                        if (dialog.inspectionInfo.is_inj == 'Y' ) {
                                            if(injData.qc_record_param == '1'){
                                                if(dialog.inspectionInfo.qc_record_param == '0')dialog.inspectionInfo.qc_record_param = '1';
                                            }else{
                                                if(dialog.inspectionInfo.qc_record_param == '1')dialog.inspectionInfo.qc_record_param = '0';
                                                else if(dialog.inspectionInfo.qc_record_param == '0')dialog.inspectionInfo.qc_record_param = '1';
                                            }
                                        }
                                    },
                                    add_btn: function (event) {
                                        if(dialog._event['pic'].isShown === 'Y'){
                                            dialog.pic_add(event);
                                        } else if(dialog._event['detail_report'].isShown === 'Y') {
                                            dialog.addRow();
                                        }
                                    },
                                    _fn: {
                                        confirm: {
                                            click: () => {
                                                dialog.confirm();
                                            }
                                        },
                                        add_row: {
                                            click: () => {
                                                dialog.addRow();
                                            }
                                        }
                                    },
                                    _event: {
                                        qc_reason_detail: {
                                            isShown: 'Y'
                                        },
                                        pic: {
                                            isShown: 'N'
                                        },
                                        detail_report: {
                                            isShown: 'N'
                                        },
                                        pcsno: {
                                            change: (pcsno, event) => {
                                                dialog.check_partial_pcsno(event)
                                            },
                                            isDisabled: "N"
                                        },
                                        check_qty: {
                                            isDisabled: "N"
                                        }
                                    },
                                    //根據NeedSN，判斷Disable for M#121894
                                    beforeShown: function () {
                                        dialog._event.pcsno.isDisabled = (dialog.NeedSN == '1') ? 'Y' : "N"
                                        dialog._event.check_qty.isDisabled = (dialog.NeedSN == '2' || dialog.NeedSN == '3') ? 'Y' : "N"
                                        if (dialog._event.check_qty.isDisabled == 'Y') $timeout(() => $rootScope.focusById('pcsno'), 1000);
                                    },
                                    check_partial_pcsno: function (e) {
                                        var check = typeof dialog.inspectionInfo.pcsno !== 'undefined';
                                        if (check && dialog.inspectionInfo.pcsno.trim() != "" && e.event.which === 13) {
                                            $MMWService.sendToServer({
                                                uri: 'ServicesSTD.Module_SN.station_partial_sn_check_process',
                                                content: {
                                                    check_type: options.type, //0首、2巡、5自、4末
                                                    op_no: dialog.inspectionInfo.op_no,
                                                    plot_no: dialog.inspectionInfo.plot_no,
                                                    plot_status: options.plotItem.status,
                                                    machine_no: dialog.inspectionInfo.machine_no,
                                                    pcs_no: dialog.inspectionInfo.pcsno,
                                                    product_no: options.product_id
                                                },
                                                error: function (data) {
                                                    $rootScope.showAlert(data.Message);
                                                }
                                            });
                                        }
                                    }
                                };
                            }
                        );
                    })
                };

        
                // 原本的標準版開窗
                function originalOpenDialog() {
                    // 不良原因
                    $MMWService.pageNumberInfoGet({
                        form_name: 'PageNo_8',
                        query_condition_info: [
                            {column_name: 'OPNo', value: options.plotItem.op_no, query_mode: 0, merge_condition_model: 'AND'}
                        ]
                    }, function(itemList){
                        opqcreason_info_get(function (data) {
                            var spc_flag = false;
                            if (config.module.filter(m => m.name == 'modulesSPC').length > 0) {
                                spc_flag = true;
                            }
                            if(config.cache.sys_parameter.IsInjectionMolding == '1' ||
                            config.cache.sys_parameter.IsInjectionMolding == 'Y' ||
                            config.cache.sys_parameter.ISINJECTIONMOLDING == '1' ||
                            config.cache.sys_parameter.ISINJECTIONMOLDING == 'Y') // 注塑模組
                            {
                                inj_eqp_info_get(function (injData) {
                                    openDialog(itemList, data, injData, spc_flag);
                                });
                            }
                            else
                                openDialog(itemList, data, {}, spc_flag);
                        });
                    });
                };

                $mddProvider.UseForm('B0207Service', () => {
                    //20200110 modify by WeiTing for M#66287 - 改成點擊首巡檢按鈕，先判斷是要走 SPC檢驗，還是 標準版開窗。
                    opqcreason_info_get(function(area){
                         // run_spc = 1  对接QMS  NeedSN = true 展示序列号
                        // 20200226 modify by WeiTing for M#67360 - SPC檢驗，要改成開窗，讓使用者可以自己調整檢驗數量。
                        judgeSpcProcess(area, check_qty = 0, run_type = 0, "","", function(data){
                            if(data.run_spc){
                                spcDialog(area,data);  
                            } 
                            else {
                                // 如果檢驗單編號是空值就走原本 標準版開窗。
                                originalOpenDialog();
                            };
                        });
                    });
                });
            };
        }]);
});
